/**
 * 功能：
 * 1. 传入 items 属性，使 TableFilterForm 可配置
 * 2. 传入 onSearch、onReset 属性，监听查询按钮、重置按钮点击事件
 */
import React, {
    useState,
    useEffect,
    useImperativeHandle,
    forwardRef,
} from 'react';
import { Form, Button } from 'antd';
import { DoubleRightOutlined } from '@ant-design/icons';
import { debounce } from 'lodash';
import hcpUtils from '@/utils/hcpUtils';
import styles from './HcpTableFilter.module.less';

const LabelText = ({ text }) => (
    <div
        style={{
            display: 'inline-block',
            // width: 70,
        }}
    >
        {text}
    </div>
);

let HcpTableFilter = ({ items, onSearch, restProps }, ref) => {
    const [form] = Form.useForm();
    const formFoldHeight = 49;
    const formItemGutter = 60;
    const [collapsed, setCollapsed] = useState(true);
    const [foldButtonVisible, setFoldButtonVisible] = useState(true);

    useImperativeHandle(ref, () => ({
        getForm: () => {
            return form;
        },
    }));

    useEffect(() => {
        const handleResize = () => {
            const FORM_DOM = document.querySelector('#table-filter > form');
            console.log('FORM_DOM.scrollHeight', FORM_DOM.scrollHeight);
            if (FORM_DOM.scrollHeight !== 52) {
                setFoldButtonVisible(true);
            } else {
                setFoldButtonVisible(false);
            }
        };
        handleResize();
        const resizeDebounced = debounce(handleResize, 300);
        hcpUtils.addEvent(window, 'resize', resizeDebounced);
        return () => {
            hcpUtils.removeEvent(window, 'resize', resizeDebounced);
        };
    }, []);

    // 监听查询按钮点击
    const handleSearch = (values) => {
        onSearch(values);
    };

    // 监听重置按钮点击
    const handleReset = () => {
        form.resetFields();
    };

    // 渲染表单项
    const renderFormItems = () => {
        return items.map((item) => {
            const { label, style, field, options, component } = item;
            return (
                <Form.Item
                    style={{
                        marginRight: 0,
                        paddingLeft: formItemGutter / 2,
                        // paddingRight: formItemGutter / 2,
                        ...style,
                    }}
                    label={<LabelText text={label} />}
                    key={field}
                    name={field}
                    {...options}
                >
                    {component}
                </Form.Item>
            );
        });
    };

    // 渲染按钮组
    const renderButtons = () => {
        return (
            <Form.Item
                style={{
                    float: 'right',
                    marginLeft: foldButtonVisible
                        ? -(formItemGutter / 2)
                        : formItemGutter / 2,
                    paddingRight: formItemGutter / 2,
                    marginRight: '0',
                    zIndex: 1,
                }}
            >
                <Button
                    style={{ marginRight: 10 }}
                    type="primary"
                    htmlType="submit"
                >
                    查询
                </Button>
                <Button onClick={handleReset}>重置</Button>
                {foldButtonVisible && (
                    <Button
                        style={{ marginLeft: 20, padding: 0 }}
                        type="link"
                        onClick={() => setCollapsed(!collapsed)}
                    >
                        {collapsed ? '展开' : '收起'}{' '}
                        <DoubleRightOutlined rotate={collapsed ? 90 : -90} />
                    </Button>
                )}
            </Form.Item>
        );
    };

    return (
        <div {...restProps} id="table-filter" style={{ width: '100%' }}>
            <Form
                form={form}
                style={{
                    marginLeft: -(formItemGutter / 2),
                    marginRight: -(formItemGutter / 2),
                    overflow: 'hidden',
                    display: 'block',
                    width: '100%',
                    ...(collapsed ? { height: formFoldHeight } : null),
                }}
                layout="inline"
                noValidate
                autoComplete="off"
                onFinish={handleSearch}
                className={styles.hcp__table__form}
            >
                {collapsed && renderButtons()}
                {renderFormItems()}
                {!collapsed && renderButtons()}
            </Form>
        </div>
    );
};

HcpTableFilter = forwardRef(HcpTableFilter);

export default React.memo(HcpTableFilter);
